<template>
  <div class="card ticket-detail-main">
    <div class="ticket-detail-title">
      <el-button type="primary" link class="backbtn" @click="cancel()">
        <el-icon :size="20"><Back /></el-icon>
      </el-button>
      <span>{{ flowTypeList[flowType] }}工单</span>
      <span v-if="businessData.module_zh"> - {{ businessData.module_zh }}</span>
      <span v-if="businessData.name"> - {{ businessData.name }}</span>
    </div>
    <div class="handle-btn">
      <el-button
        v-if="isNew || (isHandle && isCurUser) || (showDelBtn && isCurUser)"
        type="primary"
        @click="submitForm()"
        :loading="loadingSubmit"
      >
        提交
      </el-button>
      <el-button
        type="primary"
        v-if="!isNew && isSubmitUser && !isOperate"
        @click="handleClick('revoke', ['撤回工单', '撤回工单'], revokeTicketApi)"
        :loading="loadingBtn.revoke"
      >
        撤回
      </el-button>
      <el-button
        v-if="isHandle && isCurUser"
        @click="handleClick('reject', ['退回至发起人', '退回工单'], rejectTicketApi)"
        :loading="loadingReject"
      >
        退回
      </el-button>
      <el-button
        v-if="showDelBtn && isCurUser"
        @click="handleClick('delete', ['删除工单', '删除工单'], deleteTicketApi)"
        :loading="loadingDelete"
      >
        删除
      </el-button>
      <el-button v-if="isNew || isSubmitUser" @click="cancel()"> 取消 </el-button>
    </div>
    <el-tabs v-model="tabsMenuValue" v-if="showDetail">
      <el-tab-pane label="工单信息" name="A">
        <TicketInfo
          ref="infoRef"
          :flow-type="flowType"
          :ticket-type="ticketType"
          :ticket-data="ticketData"
          :business-data="businessData"
          :asset-init-params="assetInitParams"
          :alarm-init-params="alarmInitParams"
          @show-flow="tabsMenuValue = 'B'"
        ></TicketInfo>
      </el-tab-pane>
      <el-tab-pane label="工单流程" name="B"><TicketFlow :flow-id="flowId"></TicketFlow></el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, watch, computed } from "vue";
import { onBeforeRouteLeave } from "vue-router";
import TicketInfo from "./components/TicketInfo.vue";
import TicketFlow from "./components/TicketFlow.vue";
import {
  createTicketApi,
  getBusinessDetailApi,
  getTicketDetailApi,
  deleteTicketApi,
  rejectTicketApi,
  revokeTicketApi
} from "@/api/modules/ticket/pending";
import { ElMessageBox, ElMessage } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { useRoute, useRouter } from "vue-router";

// 获取当前路由对象
const route = useRoute();
const router = useRouter();
const business_id = computed(() => route.query.business_id as string);
const ticket_id = computed(() => route.query.id as string);
const asset_id = computed(() => route.query.asset_id as string);
const assetInitParams = computed(() => (asset_id.value ? { ids: asset_id.value } : {}));
const alarm_id = computed(() => route.query.alarm_id as string);
const alarmInitParams = computed(() => (alarm_id.value ? { ids: alarm_id.value } : {}));
const flowType_router = computed(() => (route.query.flowType || "NEW") as string);
const ticketType = computed(() => (route.query.ticketType || "normal") as string);
const flowType = ref(flowType_router.value);

// 离开当前页面是否提醒
const leaveNotice = ref(true);
const showDetail = ref(false);
const flowTypeList = reactive({
  NEW: "新建",
  REVIEW: "审核",
  PENDING: "处理",
  REVOKED: "审核",
  REJECTED: "审核"
});
const tabsMenuValue = ref("A");
const loadingSubmit = ref(false);
const loadingDelete = ref(false);
const loadingReject = ref(false);
const businessData = ref<any>({});
const ticketData = ref<any>({});
// const assetData = ref<any>([]);
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfoGet);
const userName = userInfo.value.username;
const userid = userInfo.value.id;
const loadingBtn = ref({
  revoke: false,
  reject: false,
  delete: false
});

// 是否是新建流程
const isNew = computed(() => flowType.value === "NEW");
// 是否是审核或处理流程的操作人
const isHandle = computed(() => ["REVIEW", "PENDING"].includes(flowType.value));
// const isHandle = computed(() => {
//   // 是否是审核和处理流程
//   const isFlow = ["REVIEW", "PENDING"].includes(flowType.value);
//   // 是否是当前流程处理人
//   const isCurUser = (ticketData.value.current_operator || []).includes(userName);
//   return isFlow && isCurUser;
// });
// 是否是当前流程处理人
const isCurUser = computed(() => (ticketData.value.current_operator || []).includes(userName));
const showDelBtn = computed(() => ["REVOKED", "REJECTED"].includes(flowType.value));
// 是否是发起人
const isSubmitUser = computed(() => Number(ticketData.value.create_by) === Number(userid));
// 此流程提交后是否操作过
const isOperate = computed(() => {
  let res = true;
  if (ticketData.value.nodes && ticketData.value.nodes.length) {
    const data = ticketData.value.nodes.filter(a => a.type !== "START" && a.results.length);
    if (!data.length) res = false;
  } else {
    res = false;
  }
  return res;
});

const getBusinessListById = async () => {
  if (business_id.value) {
    await getBusinessDetailApi(business_id.value)
      .then(res => {
        businessData.value = res.data || {};
      })
      .catch(error => console.log(error));
  }
  refleshData();
};

const getTicketListById = async () => {
  if (ticket_id.value) {
    let { data } = await getTicketDetailApi(ticket_id.value);
    ticketData.value = data || {};
    flowType.value = ticketData.value.status;
  }
  refleshData();
};

// const getAssetListById = async () => {
//   if (asset_id.value) {
//     let { data } = await getAssetDetailApi(asset_id.value);
//     assetData.value = data || [];
//   }
//   refleshData();
// };

const infoRef = ref<InstanceType<typeof TicketInfo> | null>(null);
const flowId = computed(() => (infoRef.value?.formCustom.workflow ? Number(infoRef.value?.formCustom.workflow) : 0));
const submitForm = async () => {
  loadingSubmit.value = true;
  const valid = await infoRef.value?.validForm();
  if (valid) {
    const form = infoRef.value?.formCustom;
    if (form) {
      const data = {
        business: form.business_id,
        name: form.name,
        desc: form.desc,
        notes: form.notes,
        attachment: form.attachment,
        opinion: form.opinion,
        workflow: form.workflow,
        asseet_no: form.asseet_no,
        source_type: form.source_type,
        source_id: form.source_id,
        priority: form.priority
      };
      createTicketApi(data)
        .then(() => {
          ElMessage.success("操作成功");
          loadingSubmit.value = false;
          leaveNotice.value = false;
          cancel();
        })
        .catch(error => {
          loadingSubmit.value = false;
          console.error(error);
          let str = "";
          console.log(error.response);
          if (error.response && error.response.data && error.response.data.message) {
            str = error.response.data.message;
          }
          ElMessage.error("操作失败" + (str.length > 0 ? ": " + str : ""));
          // this.cancel()
        });
    } else {
      loadingSubmit.value = false;
    }
  } else {
    loadingSubmit.value = false;
  }
};

// const rejectTicket = () => {
//   loadingReject.value = false;
//   ElMessageBox.confirm("是否确认退回至发起人？", "退回工单", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消"
//   })
//     .then(() => {
//       rejectTicketApi(ticket_id.value)
//         .then(res => {
//           console.log(res);
//           ElMessage.success("操作成功");
//           loadingReject.value = false;
//           leaveNotice.value = false;
//           cancel();
//         })
//         .catch(error => {
//           loadingReject.value = false;
//           console.error(error);
//           ElMessage.error("操作失败");
//           // this.cancel()
//         });
//     })
//     .catch(() => {
//       // 不执行操作
//     });
// };

// const revokeTicket = () => {
//   loadingReject.value = false;
//   ElMessageBox.confirm("是否确认撤回工单？", "撤回工单", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消"
//   })
//     .then(() => {
//       revokeTicketApi(ticket_id.value)
//         .then(res => {
//           console.log(res);
//           ElMessage.success("操作成功");
//           loadingReject.value = false;
//           leaveNotice.value = false;
//           cancel();
//         })
//         .catch(error => {
//           loadingReject.value = false;
//           console.error(error);
//           ElMessage.error("操作失败");
//           // this.cancel()
//         });
//     })
//     .catch(() => {
//       // 不执行操作
//     });
// };

// const deleteTicket = () => {
//   loadingDelete.value = false;
//   ElMessageBox.confirm("是否确认删除工单？", "删除工单", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消"
//   })
//     .then(async () => {
//       deleteTicketApi(ticket_id.value)
//         .then(res => {
//           console.log(res);
//           ElMessage.success("操作成功");
//           loadingDelete.value = false;
//           leaveNotice.value = false;
//           cancel();
//         })
//         .catch(error => {
//           loadingDelete.value = false;
//           console.error(error);
//           ElMessage.error("操作失败");
//           // this.cancel()
//         });
//     })
//     .catch(() => {
//       // 不执行操作
//     });
// };

const handleClick = (type, msg, api) => {
  loadingBtn.value[type] = true;
  ElMessageBox.confirm(`是否确认${msg[0]}？`, msg[1], {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
    .then(async () => {
      api(ticket_id.value)
        .then(res => {
          console.log(res);
          ElMessage.success("操作成功");
          loadingBtn.value[type] = false;
          leaveNotice.value = false;
          cancel();
        })
        .catch(error => {
          loadingBtn.value[type] = false;
          console.error(error);
          // ElMessage.error("操作失败");
          // this.cancel()
        });
    })
    .catch(() => {
      // 不执行操作
    });
};

const cancel = () => {
  router.go(-1);
};

const refleshData = () => {
  showDetail.value = false;
  setTimeout(() => {
    showDetail.value = true;
  }, 100);
};

watch(
  () => business_id.value,
  () => {
    getBusinessListById();
  },
  { deep: true, immediate: true }
);
watch(
  () => ticket_id.value,
  () => {
    getTicketListById();
  },
  { deep: true, immediate: true }
);
// watch(
//   () => asset_id.value,
//   () => {
//     getAssetListById();
//   },
//   { deep: true, immediate: true }
// );

// watch(
//   () => ticketData,
//   () => {
//     refleshData();
//   },
//   { deep: true, immediate: true }
// );

// 使用 ref 创建响应式数据
const beforeunloadFn = (e: BeforeUnloadEvent) => {
  e = e || window.event;
  if (e) {
    e.returnValue = "关闭提示";
  }
  return "关闭提示";
};
// 挂载和卸载生命周期钩子
onMounted(() => {
  window.addEventListener("beforeunload", beforeunloadFn);
  getBusinessListById();
  getTicketListById();
});
onUnmounted(() => {
  window.removeEventListener("beforeunload", beforeunloadFn);
});
// 确认离开的方法
const confirmLeave = (next: any) => {
  const confirmResult = window.confirm("确定要离开当前页面吗？ 未保存会导致当前创建或修改的内容丢失");
  if (confirmResult) {
    next();
  } else {
    next(false);
  }
};
// beforeRouteLeave 守卫
const beforeRouteLeave = (to: any, from: any, next: any) => {
  if (leaveNotice.value) {
    confirmLeave(next);
  } else {
    next();
  }
};
onBeforeRouteLeave(beforeRouteLeave);
</script>

<style lang="scss" scoped>
.ticket-detail-main {
  position: relative;
  display: flex;
  flex-direction: column;
  row-gap: 16px;
  height: 100%;
  .backbtn {
    margin-right: 12px;
    cursor: pointer;
  }
  .ticket-detail-title {
    font-size: 20px;
    font-weight: 600;
    color: var(--el-color-primary);
  }
  .handle-btn {
    position: absolute;
    top: 36px;
    right: 32px;
    z-index: 2;
  }
  .el-tabs {
    flex: 1;
    min-height: 0;
    :deep(.el-tabs__item) {
      margin-bottom: 6px;
    }
    :deep(.el-tabs__content) {
      overflow: auto;
    }
  }
}
</style>
